package com.ry.demo.concurrent.demo.base;

/**
 * @Author: lihui
 * @Date: 2021-12-02 09:34
 * @Description:
 */
public class InterruptDemo {

    public static void main(String[] args) throws InterruptedException {

        MyThread thread = new MyThread();
        thread.start();

        Thread.sleep(1000);

        thread.setShouldRun(false);
        thread.interrupt(); // 调用 interrupt()方法，可以让处于休眠的线程 抛出异常，从而实现唤醒线程的功能
    }

    private static class MyThread extends Thread {

        private Boolean shouldRun = true;

        @Override
        public void run() {
            while (shouldRun){
                System.out.println("线程执行");

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    System.out.println("子线程报错了,当前线程中断标志为："+shouldRun);
                    e.printStackTrace();
                }
            }
        }

        public void setShouldRun(Boolean shouldRun){
            this.shouldRun = shouldRun;
        }
    }

    public static class InterruptTest {
        public static void main(String[] args) throws InterruptedException {

            Thread threadA = new Thread(() -> {
                while (!Thread.currentThread().isInterrupted()){
                    System.out.println("aa");
                }
                System.out.println("Thread 标志位被修改为 中断了");
            });
            threadA.start();
            Thread.sleep(100);

            threadA.interrupt();

            System.out.println("main Thread "+threadA.isInterrupted());
        }
    }


}
